package persion.leetcode;

/**
 * Created by wangyifei on 19/7/14.
 * 在 ascii 中，字符串 0 使用数字 48 表示，也就说，我们可以使用 char 类型的变量减去 48 就可以得到对应的整形数字
 * << >> 位操作的优先级低于 + - * /
 */
public class atoi {

    public static void main(String[] args) {
       // example1 "123" --> 123
//       System.out.println((1<<31)-1);
       System.out.println("123 --> "+myitos("123"));
       System.out.println("1212213 --> "+myitos("1212213"));
//       example1 "+/-", "+123" --> "123" , "-1998" --> "-1998"
       System.out.println("-123 --> "+myitos("-123"));
       // example2 "   -21221" --> -21221
       System.out.println("   -21221 --> "+myitos("   -21221"));
       // example3 "   -21221" --> -21221
       System.out.println("   +21221 --> "+myitos("   +21221"));
       // example4 "   a21221" --> -21221
       System.out.println("   a21221 --> "+myitos("   a21221"));
       // example5 "   a21221" --> -21221
       System.out.println("   121aa221 --> "+myitos("   121aa221"));
       // example6 -91283472332 --> -2147483648
       System.out.println("-91283472332 -->"+myitos("-91283472332"));
       // example6 -91283472332 --> -2147483648
       System.out.println("  -91283472332 -->"+myitos("  -91283472332"));
    }


    private static int myitos(String str){
       int rs = 0 ;
       if(null == str || str.length() == 0 ){
           return 0 ;
       }
       char[] chars = str.toCharArray();



       int positive = 1 ;
       int start = 0 ;


       if(32 == chars[0]){
          for(char c : chars) {
             if(32 == c) {
                start ++ ;
             }else{
                break;
             }
          }
       }


       if(!((chars[start] >= '0' && chars[start] <= '9') || chars[start] == '-' || chars[start] == '+')){
        return 0 ;
       }
       if(chars[start] == '-' || chars[start] == '+'){
          // 43 是 + 对应的数字
          positive = ( chars[start] - '-') == 0 ? -1 : 1 ;
          start ++ ;
       }
       if(str.length() + (chars[start] == '-' || chars[start] == '+'?-1:0)>10){
          start = start + (str.length() - start - 1 +(chars[start] == '-' || chars[start] == '+'?-1:0) - 10 );
       }

       for(int i = start ; i < chars.length;i++){
           if(chars[i] >= '0' && chars[i] <= '9'){
               rs = rs*10 + chars[i] - 48 ;
           }else {
               break;
           }
       }

        return positive*rs ;
    }

}
